package com.thinkingcoder.tcgateway.web.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebHandler;

import com.thinkingcoder.tcgateway.filter.GatewayFilter;
import com.thinkingcoder.tcgateway.plugin.GatewayPlugin;
import com.thinkingcoder.tcgateway.plugin.chain.DefaultGatewayPluginChain;

import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

/**
 * gateway web handler
 */
@Slf4j
@Component("gatewayWebHandler")
public class GatewayWebHandler implements WebHandler {

    @Autowired
    List<GatewayPlugin> plugins;

    @Autowired
    List<GatewayFilter> filters;

    @Override
    public Mono<Void> handle(ServerWebExchange exchange) {
        log.info(" ======>>>>>> TC-Gateway WebHandler ...");

        if (plugins == null || plugins.isEmpty()) {
            String mockResp = """
                {
                    "result":"Non-Plugin"
                }
                """;
            return exchange.getResponse()
                .writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(mockResp.getBytes())));
        }

        for (GatewayFilter filter : filters) {
            filter.filter(exchange);
        }

        return new DefaultGatewayPluginChain(plugins).handle(exchange);

    }

}
